<template>
  <div class="main">
    <div>
      <ElCard>
        <template #header> 用户登录 </template>

        <div>
          <ElForm :model="user" ref="myform" :rules="rules">
            <ElFormItem prop="username">
              <ElInput v-model="user.username" placeholder="登录名"></ElInput>
            </ElFormItem>

            <ElFormItem prop="password">
              <ElInput v-model="user.password" :show-password="true" placeholder="密码"></ElInput>
            </ElFormItem>

            <ElFormItem>
              <ElButton @click="login(myform)" type="primary">登录</ElButton>
              <ElButton type="danger">重填</ElButton>
            </ElFormItem>
          </ElForm>
        </div>
      </ElCard>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

import { ElButton, ElCard, ElForm, ElFormItem, ElInput, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { TbUser } from '../../ts/UserInfo'
import { BaseResult } from '../../ts/BaseResult'
import { ApiService } from '../../ts/ApiService'
import Tools from '../../ts/Tools'

import { store } from '../../store/index'

const { updateUser } = store()

const router = useRouter()

const user = ref(new TbUser())
const myform = ref<FormInstance>()

function checkName(rule: any, value: string, callback: any) {
  if (/^[\S]{4,16}$/.test(value)) {
    callback()
  } else {
    callback(new Error('用户名格式不正确'))
  }
}

const rules = reactive<FormRules<TbUser>>({
  username: [
    {
      required: true,
      message: '登录用户名必须填写',
    },
    { validator: checkName },
  ],
  password: [
    {
      required: true,
      message: '登录密码必须填写',
    },
  ],
})

function login(myform) {
  myform.validate((valid: boolean, fileds: any) => {
    console.log('校验结果：', valid, fileds)
    if (!valid) {
      return
    }
    let suser = Tools.concatJson(user.value)
    suser.password = Tools.md5(suser.password)

    ApiService.post('/user/auth/login', suser, (data: BaseResult) => {
      if (data.success) {
        // 通过状态管理获取登录用户的信息
        updateUser(() => {
          
          ElMessageBox.alert(data.message).then(() => {
            console.log('登录成功')
            router.push('/user/main')
          })

        })
      }
    })
  })
}
</script>

<style lang="scss" scoped>
.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  > div {
    transform: translateY(-10vh);
    min-width: 25vw;
  }
}
</style>
